<template>
  <div class="object_recognition">
    <video
      id="video" ref="videoRef" :width="videoSize.width" :height="videoSize.height" webkit-playsinline muted playsinline
      object-fit="cover"
    />
    <img class="hexagon" src="https://jwc-static.jdwxk.com/imgs/ar/hexagon.png" alt="">
    <div v-show="result !== ''" class="tip">
      {{ tip }}
    </div>
    <div v-show="result !== ''" class="tip2">
      {{ tip2 }}
    </div>
    <GetCardTip ref="GetCardTipRef" />

    <!-- <van-button type="primary" class="startScan" @click="openCamera">开始扫描</van-button> -->
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showFailToast } from 'vant'

import GetCardTip from '@/components/getCardTip.vue'

import { baiduVerify } from '@/api/activities'
import { arResultMath } from '@/views/activities/config.js'

import { useActivityStoreG } from '@/store/modules/activity'

const route = useRoute()
const router = useRouter()

// const result_keys = ref([])
const videoSize = reactive({
  width: window.innerWidth,
  height: window.innerHeight,
})
const mediaStream = ref(null)
const result = ref('')
const tip = ref('对准目标，自动扫描')
const tip2 = ref('')

const state = reactive({
  mode: 'entrance', // entrance 活动入口(默认)  recognition 识别具体物品
  targetObject: [],
})

onMounted(async () => {
  state.mode = 'entrance'
  getKeyWord()
  setTimeout(() => {
    openCamera()
  })
})
onUnmounted(() => {
  console.log('onUnmounted')
  closeCamera()
})
// 获取待识别物品的关键字，用于判单是否识别到了指定的物品
function getKeyWord() {
  const query = route.query
  if (query && query.targetObject) {
    state.mode = 'recognition'
    console.log('待识别物品', query, JSON.parse(route.query.targetObject))
    state.targetObject = JSON.parse(route.query.targetObject)
  }
  else {
    state.mode = 'entrance'
  }
}

async function objectRecognition(base64Img) {
  const res = await baiduVerify({ base64File: base64Img })
  console.log('baiduVerify', res)
  if (res.data.result && res.data.result.length > 0) {
    const result_arr = res.data.result
    console.log('result_arr', result_arr, Math.max(...result_arr.map((j) => {
      return j.score
    })))

    const result_item = result_arr.find((i) => {
      return i.score === Math.max(...result_arr.map((j) => {
        return j.score
      }))
    })
    console.log('识别结果', result_item)
    result.value = result_item
  }
  else {
    console.log('无结果')
  }
}

const videoRef = ref()
async function openCamera() {
  try {
    console.log('navigator', navigator)
    console.log('navigator.mediaDevices', navigator.mediaDevices)
    console.log('navigator.mediaDevices.getUserMedia', navigator.mediaDevices.getUserMedia)
    mediaStream.value = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
    console.log('mediaStream.value', mediaStream.value)
    videoRef.value.srcObject = mediaStream.value
    videoRef.value.play()
    // const p = videoRef.value.play()
    // if (p !== undefined) {
    //   p.then(() => {
    //     // videoRef.value.pause()
    //     setTimeout(() => {
    //       videoRef.value.play()
    //     }, 0)
    //   }).catch((e) => {
    //     console.log(e, 'undefinedPlay报错')
    //   })
    // }
    const canvas = document.createElement('canvas')
    canvas.width = videoRef.value.width
    canvas.height = videoRef.value.height
    const ctx = canvas.getContext('2d')
    setTimeout(() => {
      uploadFile(ctx, canvas)
    }, 1000)
  }
  catch (error) {
    console.log('error', `${error}`, typeof (error))
    // showFailToast(`${error}`)
    showFailToast(`摄像头权限获取失败`)
    console.error('openCamera error2', error)
  }
}
function closeCamera() {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach((track) => {
      track.stop() // 停止所有的track，也就是摄像头
    })
    mediaStream.value = null // 重置MediaStream对象
  }
}

const GetCardTipRef = ref()
function openGetCardTip(res, routerBack) {
  GetCardTipRef.value.open(res, routerBack)
}
const activityStore = useActivityStoreG()
const colectCardList = computed(() => activityStore.getColectCardList)

async function uploadFile(ctx, canvas) {
  if (!videoRef.value || videoRef.value.paused || videoRef.value.ended) {
    return
  }
  ctx.drawImage(videoRef.value, 0, 0, videoSize.width, videoSize.height)
  // ctx.drawImage(videoRef.value, videoSize.width/2 - 150, videoSize.height/2 - 173, 300, 346, videoSize.width/2 - 150, videoSize.height/2 - 173,300, 346);
  const base64String = canvas.toDataURL('image/jpeg', 0.5)
  console.log('base64String 0.5', base64String.length)

  const base64Img = base64String.replace('data:image/jpeg;base64,', '')
  await objectRecognition(base64Img)
  // 判断是否对应待识别物品的关键词

  console.log('arResultMath', arResultMath)
  tip2.value = `与活动标识物相似度：${(result.value.score * 100).toFixed(1)}%`
  if (result.value.score < 0.4) {
    uploadFile(ctx, canvas)
    return
  }
  if (state.mode === 'entrance') {
    const matchObject = arResultMath.filter((i) => {
      return i.imgId === result.value.brief
    })
    console.log('matchObject', matchObject)
    if (matchObject.length > 0 && matchObject[0].type === 'activity') {
      console.log('识别成功-entrance', matchObject[0])
      router.push({
        path: matchObject[0].path,
        query: matchObject[0].query,
      })
    }
    else if (matchObject.length > 0 && matchObject[0].type === 'collectCard') {
      console.log('识别成功-entrance', matchObject[0])
      console.log('待识别物', colectCardList.value)
      console.log('matchObject[0]', matchObject[0])
      const matchTarget = colectCardList.value.filter((item) => {
        return item.name === matchObject[0].name
      })
      console.log('matchTarget', matchTarget)
      if (matchTarget.length > 0) {
        if (matchTarget[0].cardPic === '') {
          openGetCardTip(matchObject[0], -1)
          const temp = JSON.parse(JSON.stringify(colectCardList.value))
          const index = colectCardList.value.findIndex((j) => {
            return j.name === matchTarget[0].name
          })
          temp[index] = { name: matchTarget[0].name, cardPic: matchObject[0].cardPic }
        }
        else {
          console.log('您已经获取该卡片')
          tip2.value = `您已经获取该卡片`
          uploadFile(ctx, canvas)
        }
      }
      else {
        console.log('匹配目标不是待寻找卡片')
        tip2.value = `当前物品不是待寻找卡片`
        uploadFile(ctx, canvas)
      }
    }
    else {
      console.log('识别成功，预设配置类型错误-entrance')
      tip2.value = `当前物品不是活动标识物`
      uploadFile(ctx, canvas)
    }
  }
  else {
    const matchObject = arResultMath.filter((i) => {
      return i.imgId === result.value.brief
    })
    if (matchObject.length > 0 && matchObject[0].type === 'activity') {
      console.log('识别成功-recognition', matchObject[0])
      // 将匹配度最高的数据与 带获取的目标比对
      console.log('state.targetObject', state.targetObject)
      console.log('matchObject[0]', matchObject[0])
      const matchTarget = state.targetObject.filter((item) => {
        return item.name === matchObject[0].name
      })
      console.log('matchTarget', matchTarget)
      if (matchTarget.length > 0) {
        if (matchTarget[0].cardPic === '') {
          openGetCardTip(matchObject[0], -1)
          const temp = JSON.parse(JSON.stringify(state.targetObject))
          const index = state.targetObject.findIndex((j) => {
            return j.name === matchTarget[0].name
          })
          temp[index] = { name: matchTarget[0].name, cardPic: matchObject[0].cardPic }
          // activityStore.setColectCardList(temp)
        }
        else {
          console.log('您已经获取该物品')
          tip2.value = `您已经获取该物品`
          uploadFile(ctx, canvas)
        }
      }
      else {
        console.log('匹配目标不是待寻找物品')
        tip2.value = `当前物品不是待寻找物品`
        uploadFile(ctx, canvas)
      }
    }
    else if (matchObject.length > 0 && matchObject[0].type === 'treasureHunt') {
      console.log('识别成功-recognition', matchObject[0])
      // 将匹配度最高的数据与 带获取的目标比对
      console.log('state.targetObject', state.targetObject)
      console.log('matchObject[0]', matchObject[0])
      const matchTarget = state.targetObject.filter((item) => {
        // return item.cardPic === matchObject[0].cardPic
        // return item.id.toString() === matchObject[0].imgId
        return item.cardPic === matchObject[0].cardPic
      })
      console.log('matchTarget', matchTarget)
      if (matchTarget.length > 0) {
        if (matchTarget[0].cardPic === '') {
          openGetCardTip(matchObject[0], -1)
          const temp = JSON.parse(JSON.stringify(state.targetObject))
          const index = state.targetObject.findIndex((j) => {
            return j.name === matchTarget[0].name
          })
          temp[index] = { name: matchTarget[0].name, cardPic: matchObject[0].cardPic }
        }
        else {
          console.log('您已经获取该宝物')
          tip2.value = `您已经获取该宝物`
          uploadFile(ctx, canvas)
        }
      }
      else {
        console.log('匹配目标不是待寻找宝物')
        tip2.value = `当前物品不是待寻找宝物`
        uploadFile(ctx, canvas)
      }
    }
    else {
      console.log('识别成功，但是没有预设配置-recognition')
      uploadFile(ctx, canvas)
    }
  }
}
</script>

<style lang="scss" scoped>
.object_recognition {
  background-color: black;
}

#video {
  object-fit: cover;
  width: 100%;
  height: 100vh;
  z-index: 100;
}

.hexagon {
  position: absolute;
  z-index: 910;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  width: 300px;
  height: 346px;
}

.tip {
  position: absolute;
  z-index: 910;
  transform: translate(-50%, -50%);
  left: 50%;
  color: white;
  top: calc(50% + 173px + 25px + 20px);
  width: 100%;
  height: 50px;
  text-align: center;
  line-height: 50px;
}

.tip2 {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  color: white;
  top: calc(50% + 173px + 25px + 20px + 30px);
  width: 100%;
  height: 50px;
  text-align: center;
  line-height: 50px;
}

.startScan {
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  color: white;
  top: calc(50% + 173px + 25px + 20px + 30px + 30px);
  width: 100%;
  height: 50px;
  text-align: center;
  line-height: 50px;
}
</style>
